package com.juma.cartridge.retryque;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

import lombok.Getter;
import lombok.Setter;

public class TaskLeaseProlong implements Delayed {

    @Setter @Getter private volatile long leaseVal;
    @Getter private long prolongVal;
    @Setter @Getter private String scanner;
    private List<Long> ids;
    public TaskLeaseProlong() {
        ids = new LinkedList<Long>();
    }

    public synchronized List<Long> getIds() {
        return ids;
    }

	public synchronized void addId(Long id) {
	    if(id!=null) {
	        ids.add(id);    
	    }
	}

	public synchronized void removeId(Long id) {
	    ids.remove(id);
	}
	
	public static TaskLeaseProlong of(TaskLease lease,List<RetryTask> tasks, int prolongVal) {
		TaskLeaseProlong tr = new TaskLeaseProlong();
		tr.setScanner(lease.getScanner());
		tr.setLeaseVal(lease.getLeaseVal());
		tr.setProlongVal(prolongVal);
		for(RetryTask task:tasks) {
		    tr.addId(task.getId());
		}
		return tr;
	}

	public void setProlongVal(int prolongVal) {
	    this.prolongVal = prolongVal;
	}
	
	public synchronized void incrLeaseVal() {
	    this.leaseVal = leaseVal+prolongVal;
	}
	
    @Override
    public int compareTo(Delayed o) {
        TaskLeaseProlong ln = (TaskLeaseProlong)o;
        long v = leaseVal-ln.getLeaseVal();
        if(v==0) {
            return 0;
        }
        if(v<0) {
            return -1;
        }
        return 1; 
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long delayMillis = leaseVal-System.currentTimeMillis()-2000;
        return unit.convert(delayMillis, TimeUnit.MILLISECONDS);
    }
    
    
}
